#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "opus.h"

#define SAMPLE_RATE 16000  // 16 kHz
#define FRAME_SIZE 960  // 20ms 的音频数据
#define CHANNELS 1

//  gcc priv/opus_decoder.c -o priv/opus_decoder -I/usr/include/opus -lopus
int main() {
    OpusDecoder *decoder;
    int error;
    short pcm[FRAME_SIZE * CHANNELS];
    unsigned char buffer[FRAME_SIZE];
    int samples_decoded;

    decoder = opus_decoder_create(SAMPLE_RATE, CHANNELS, &error);
    if (error != OPUS_OK) {
        fprintf(stderr, "dencoder initialization error: %d\n", error);
        return 1;
    }

    while (1) {
        size_t bytes_read = read(0, buffer, sizeof(buffer));  // 从 stdin 读取 Opus 数据
        if (bytes_read == 0) break;

        samples_decoded = opus_decode(decoder, buffer, bytes_read, pcm, FRAME_SIZE, 0);
        if (samples_decoded < 0) {
            fprintf(stderr, "decoding error: %d\n", samples_decoded);
            break;
        }

        write(1, pcm, samples_decoded * CHANNELS * sizeof(short));  // 将 PCM 数据写入 stdout
    }

    opus_decoder_destroy(decoder);
    return 0;
}